package com.ruijie.autotest.log.impl.validate;

import com.ruijie.autotest.log.common.sql.SqlField;
import com.ruijie.autotest.log.core.validate.IValidator;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.function.UnaryOperator;

public class SqlMappedExistingValidator implements IValidator {
	private final SqlField sqlField;

	private final UnaryOperator<String> mapper;

	public SqlMappedExistingValidator(SqlField sqlField, UnaryOperator<String> mapper) {
		this.sqlField = sqlField;
		this.mapper = mapper;
	}

	@Override
	public boolean validate(String actualValue) {
		try {
			return sqlField.countOccurrencesOf(actualValue, mapper) > 0;
		} catch (SQLException e) {
			throw new RuntimeException("validation failed.", e);
		}
	}

	public static SqlMappedExistingValidator mappedVerification(String pattern, UnaryOperator<String> mapper, DataSource dataSource) {
		return new SqlMappedExistingValidator(SqlField.createSqlField(dataSource, pattern), mapper);
	}
}
